package com.yanh.user.controller;

import com.yanh.common.exception.BadRequestException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import com.yanh.common.security.UserContext;
import com.yanh.common.utils.BeanUtil;
import com.yanh.common.utils.CollUtil;
import com.yanh.user.domain.Address;
import com.yanh.user.domain.AddressDTO;
import com.yanh.user.service.IAddressService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *  前端控制器
 */
@RestController
@RequestMapping("/address")
@RequiredArgsConstructor
@Tag(name="收货地址管理接口",description = "收货地址管理接口")
public class AddressController {

    private final IAddressService addressService;

    @Operation(summary = "根据id查询地址",description = "根据id查询地址")
    @GetMapping("{addressId}")
    public AddressDTO findAddressById(@PathVariable("addressId") Long id) {
        // 1.根据id查询
        Address address = addressService.getById(id);
        // 2.判断当前用户
        Long userId = UserContext.getUser();
        if(!address.getUserId().equals(userId)){
            throw new BadRequestException("地址不属于当前登录用户");
        }
        return BeanUtil.copyBean(address, AddressDTO.class);
    }
    @Operation(summary = "查询当前用户地址列表",description = "查询当前用户地址列表")
    @GetMapping()
    public List<AddressDTO> findMyAddresses() {
        // 1.查询列表
        List<Address> list = addressService.query().eq("user_id", UserContext.getUser()).list();
        // 2.判空
        if (CollUtil.isEmpty(list)) {
            return CollUtil.emptyList();
        }
        // 3.转vo
        return BeanUtil.copyList(list, AddressDTO.class);
    }
}